package com.code.train.exceptionHandler;

import cn.hutool.core.util.StrUtil;
import com.code.train.exception.BusinessException;
import com.code.train.resp.CommonResp;
import com.code.train.respCode.RespCode;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * ControllerExceptionHandler
 * 全局异常处理器
 * @param
 * @author 南汉卿
 * @return
 * @date 2025/8/3 19:37
 */
@RestControllerAdvice
@Slf4j
public class ControllerExceptionHandler {

    @ExceptionHandler(Exception.class)
    public CommonResp<String> handle(Exception e)throws Exception{
         log.info("seata全局事务ID: {}", RootContext.getXID());
         // 如果是在一次全局事务里出异常了，就不要包装返回值，将异常抛给调用方，让调用方回滚事务
         if (StrUtil.isNotBlank(RootContext.getXID())) {
             throw e;
         }
        log.info("系统异常: {}",e.getMessage());
        return CommonResp.fail("系统异常，请联系管理人员");
    }

    @ExceptionHandler(BusinessException.class)
    public CommonResp<String> handle(BusinessException e){
        log.info("业务异常: {}",e.getE().getDesc());
        return CommonResp.fail(e.getE());
    }

    @ExceptionHandler(BindException.class)
    public CommonResp<String> handle(BindException e){

        String bindMessage = e.getBindingResult().getFieldErrors().stream()
                .map(file -> file.getField() + ":" + file.getDefaultMessage())
                .collect(Collectors.joining("; "));
        log.info("参数校验异常: {}",bindMessage);
        return  CommonResp.fail(RespCode.VALIDATION_ERROR.getCode(),bindMessage);
    }


}
